import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_stream_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import '../../../app_main.dart';

///考勤规则设置viewmodel
class CheckInRuleViewModel extends BaseViewModel {
  DateTime startTime;
  DateTime endTime;

  ///规则ID
  String arid;
  VgStreamController<bool> controller;
  VgStreamController<bool> setRuleController;

  CheckInRuleViewModel(BaseState<StatefulWidget> state) : super(state) {
    controller = newAutoReleaseBroadcast();
    setRuleController = newAutoReleaseBroadcast();
  }

  ///设置开始时间
  void setStartTime(DateTime time) {
    startTime = time;
    controller.add(judgeCommit());
  }

  ///设置下班时间
  void setEndTime(DateTime time) {
    endTime = time;
    controller.add(judgeCommit());
  }

  ///设置规则
  void commit() {
    var params = {
      "authId": UserRepository.getInstance().authId ?? "",
      "delflg": "00"
    };
    if (arid == null) {
      //新增
      if (startTime == null && endTime == null) {
        //未设置时直接返回成功
        setRuleController.add(true);
        return;
      }
      params["dutytime"] = DateUtil.formatDate(startTime, format: "HH:mm");
      params["offdutytime"] = DateUtil.formatDate(endTime, format: "HH:mm");

    } else {
      params["arid"] = arid;
      if (startTime == null && endTime == null) {
        //未设置时表示删除
        params["delflg"] = "01";
        params["dutytime"] = '';
        params["offdutytime"] = '';
      }else{
        params["dutytime"] = DateUtil.formatDate(startTime, format: "HH:mm");
        params["offdutytime"] = DateUtil.formatDate(endTime, format: "HH:mm");
      }
    }

    loading(true);
    VgHttpUtils.get(NetApi.SAVE_CHECK_IN_RULE,
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          loading(false);
          setRuleController.add(true);
        }, onError: (msg) {
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///判断是否提交
  bool judgeCommit() {
    return (startTime == null && endTime == null) ||
        (startTime != null && endTime != null);
  }
}
